package com.guomw.report.service.service.impl;

import com.guomw.report.service.entity.DetectionIndex;
import com.guomw.report.service.entity.DetectionIndex;
import com.guomw.report.service.models.PageView;
import com.guomw.report.service.repository.DetectionIndexRepository;
import com.guomw.report.service.service.DetectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class DetectionServiceImpl implements DetectionService {

    @Autowired
    private DetectionIndexRepository detectionIndexRepository;


    @Override
    public PageView<DetectionIndex> searchList(Long reportId, String code, int pageIndex) {
        Pageable pageable = new PageRequest(pageIndex - 1, 10, new Sort(Sort.Direction.ASC, "sort"));
        Specification<DetectionIndex> specification = (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();

            predicates.add(builder.equal(root.get("reportId").as(String.class), reportId));

            if (!StringUtils.isEmpty(code)) {
                predicates.add(builder.like(root.get("code").as(String.class), "%" + code + "%"));
            }
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<DetectionIndex> page = detectionIndexRepository.findAll(specification, pageable);
        PageView<DetectionIndex> pageView = new PageView<>();
        pageView.setPageCount(page.getTotalPages());
        pageView.setTotalCount(page.getTotalElements());
        pageView.setList(page.getContent());
        return pageView;

    }

}
